package com.regex.web.controller.qybz;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.regex.web.common.excel.ExportExcel;
import com.regex.web.common.excel.ImportExcel;
import com.regex.web.entity.qybz.ClQtbzCjrzfbzDTO;
import com.regex.web.service.qybz.IClQtbzCjrzfbzService;
import com.regex.web.service.qybz.IClQybzRybtService;
import com.regex.web.utils.AjaxUtil;
import com.regex.web.utils.Contant;
import com.regex.web.utils.QueryResult;
import com.regex.web.vo.ImportResultVO;
import com.regex.web.vo.LayTableDataVO;
import com.regex.web.vo.ResultVO;

/**
 * <p>
 * 残疾人住房补助 前端控制器
 * </p>
 *
 * @author zzl
 * @since 2021-08-10
 */
@Controller
@RequestMapping("sys/clQtbzCjrzfbz")
public class ClQtbzCjrzfbzController {

	private final static Logger logger = LoggerFactory.getLogger(ClQtbzCjrzfbzController.class);
	
	@Autowired
	private IClQtbzCjrzfbzService IClQtbzCjrzfbzService;
	
	/**
	 * 分页查询
	 * @param page
	 * @param model
	 * @param clQtbzCjrzfbzDTO
	 * @return
	 */
	@GetMapping("show")
	public String show() {
		return "sys/clQtbzCjrzfbz/show";
	}
	
	@RequestMapping("getycxbz")
	@ResponseBody
	public ResultVO<List<Map>>  getycxbz(){
		List<Map> map = IClQtbzCjrzfbzService.getnf();
		List<Map> nfs=IClQtbzCjrzfbzService.getnf();
		System.out.println(nfs.toString());
		map.clear();
		for (int i = 0; i < nfs.size(); i++) {
			String nf=nfs.get(i).get("nf").toString();
			System.err.println(nf);
			List<Map> maps=IClQtbzCjrzfbzService.getycxbz(nf);
			for (int j = 0; j < maps.size(); j++) {
				map.add(maps.get(j));
			}
		}
		System.err.println(map.toString());

		
		return  ResultVO.success(map, ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
		
	}
	@RequestMapping("getPageData")
	public void getPageData(HttpServletResponse response,
			ClQtbzCjrzfbzDTO clQtbzCjrzfbzDTO, String limit, String page,String bjsj) {
		
		LayTableDataVO<ClQtbzCjrzfbzDTO> result = new LayTableDataVO<ClQtbzCjrzfbzDTO>();
		try {
				if (StringUtils.isEmpty(limit)) {
					limit = Contant.NONMAL_PAGE_SIZE_TEN + "";
				}
				if (StringUtils.isEmpty(page)) {
					page = Contant.NONMAL_PAGE_START + "";
				}
				System.out.println(bjsj+"========办结时间");
				if(bjsj==null||bjsj.equals("")){
					QueryWrapper<ClQtbzCjrzfbzDTO> param = new QueryWrapper<ClQtbzCjrzfbzDTO>();
					if(StringUtils.isNotEmpty(clQtbzCjrzfbzDTO.getXingMing())){
						param.eq("XingMing", clQtbzCjrzfbzDTO.getXingMing());	
					}
					if(StringUtils.isNotEmpty(clQtbzCjrzfbzDTO.getCanJiRenZhengCanJiJunRenZhengH())){
						param.eq("CanJiRenZhengCanJiJunRenZhengH", clQtbzCjrzfbzDTO.getCanJiRenZhengCanJiJunRenZhengH());	
					}
					param.orderByDesc("create_time");
					Page<ClQtbzCjrzfbzDTO> pageParam = new Page<ClQtbzCjrzfbzDTO>();
					
					pageParam.setSize(Integer.parseInt(limit));
					pageParam.setCurrent(Integer.parseInt(page));
					
			        QueryResult<ClQtbzCjrzfbzDTO> pageResult = IClQtbzCjrzfbzService.page(pageParam, param);
					
					result.setData(pageResult.getDatas());
					result.setCode(0);
					result.setCount(pageResult.getTotalDataCount());
			
				}else{
					if(bjsj.equals("是")){
						  System.out.println("执行办结");
						 Integer count = IClQtbzCjrzfbzService.selectCount();
					        System.out.println(count);
					        
					        Map<String , Object> map=new HashMap<>();
					        map.put("startIndex", Integer.parseInt(page));
					        map.put("pageSize", Integer.parseInt(limit));
					        List<ClQtbzCjrzfbzDTO> list = IClQtbzCjrzfbzService.selectForPage4(map);
					    	result.setData(list);
							result.setCode(0);
							result.setCount(count);
					}else{
						QueryWrapper<ClQtbzCjrzfbzDTO> param = new QueryWrapper<ClQtbzCjrzfbzDTO>();
						if(StringUtils.isNotEmpty(clQtbzCjrzfbzDTO.getXingMing())){
							param.eq("XingMing", clQtbzCjrzfbzDTO.getXingMing());	
						}
						if(StringUtils.isNotEmpty(clQtbzCjrzfbzDTO.getCanJiRenZhengCanJiJunRenZhengH())){
							param.eq("CanJiRenZhengCanJiJunRenZhengH", clQtbzCjrzfbzDTO.getCanJiRenZhengCanJiJunRenZhengH());	
						}
						param.orderByDesc("create_time");
						Page<ClQtbzCjrzfbzDTO> pageParam = new Page<ClQtbzCjrzfbzDTO>();
						
						pageParam.setSize(Integer.parseInt(limit));
						pageParam.setCurrent(Integer.parseInt(page));
						
				        QueryResult<ClQtbzCjrzfbzDTO> pageResult = IClQtbzCjrzfbzService.page(pageParam, param);
						
						result.setData(pageResult.getDatas());
						result.setCode(0);
						result.setCount(pageResult.getTotalDataCount());
					}
					
				}
		} catch (Exception e) {
			result.setCode(500);
			AjaxUtil.ajaxJsonSucMessage(response, result);
			e.printStackTrace();
		}
		AjaxUtil.ajaxJsonSucMessage(response, result);
	}
	
	/**
	 * 编辑/新增
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("input")
    public String toSave(@ModelAttribute("id")  String id) {
        return "sys/clQtbzCjrzfbz/input";
    }
    
    @GetMapping("get/{id}")
	@ResponseBody
    public ResultVO<ClQtbzCjrzfbzDTO> getData(@PathVariable String id) {
	    ClQtbzCjrzfbzDTO clQtbzCjrzfbzDTO = IClQtbzCjrzfbzService.getById(id);
        return ResultVO.success(clQtbzCjrzfbzDTO, ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
    }
    
    /**
	 * 保存
	 * @param clQtbzCjrzfbzDTO
	 * @param response
	 */
    @PostMapping("save")
	@ResponseBody
	public ResultVO<String> save(@Valid  @RequestBody ClQtbzCjrzfbzDTO clQtbzCjrzfbzDTO, HttpServletResponse response) {
		ResultVO<String> result = new ResultVO<String>();
		boolean flag = false;
		if(StringUtils.isNotEmpty(clQtbzCjrzfbzDTO.getId())) {
			clQtbzCjrzfbzDTO.setUpdateTime(new Date());
			flag = IClQtbzCjrzfbzService.updateById(clQtbzCjrzfbzDTO);
			if(flag) {
            	return ResultVO.success();
            }
		} else {
			clQtbzCjrzfbzDTO.setIsDel(Contant.is_del_undelete);
			clQtbzCjrzfbzDTO.setUpdateTime(new Date());
			clQtbzCjrzfbzDTO.setCreateTime(new Date());
			flag = IClQtbzCjrzfbzService.save(clQtbzCjrzfbzDTO);
			if(flag) {
            	return ResultVO.success();
            }
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("detial")
    public String detial(String id, Model model) {
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	ClQtbzCjrzfbzDTO clQtbzCjrzfbzDTO = IClQtbzCjrzfbzService.getById(id);
	            model.addAttribute("clQtbzCjrzfbzDTO", clQtbzCjrzfbzDTO);
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("detial page is Exception!");
		}
        return "sys/clQtbzCjrzfbz/detial";
    }
	
	/**
	 * 删除
	 * @param id
	 * @param response
	 */
	@RequestMapping("del")
    public void del(String id, HttpServletResponse response) {
        int n = 0;
        try {
	        if(StringUtils.isNotEmpty(id)) {
	        	boolean flag = IClQtbzCjrzfbzService.removeById(id);
	        	if(flag) {
	        		n = 1;
	        	}
	        } else {
	        	n = 2;
	        }
        } catch (Exception e) {
			e.printStackTrace();
			logger.error("del page is Exception!");
		}
        AjaxUtil.ajaxJsonSucMessage(response, n);
    }
    
    /**
	 * 导出
	 * @param response
	 * @param clQtbzCjrzfbzDTO
	 * @return
	 */
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(HttpServletResponse response, @ModelAttribute("clQtbzCjrzfbzDTO") ClQtbzCjrzfbzDTO clQtbzCjrzfbzDTO) {
        try {
            QueryWrapper<ClQtbzCjrzfbzDTO> param = new QueryWrapper<ClQtbzCjrzfbzDTO>();
			param.orderByDesc("create_time");
        	String fileName = "数据"+(new Date()).getTime()+".xlsx";
            
            List<ClQtbzCjrzfbzDTO> datas = IClQtbzCjrzfbzService.list(param);
            new ExportExcel("数据", ClQtbzCjrzfbzDTO.class).setDataList(datas).write(response, fileName).dispose();
            return null; 
        } catch (Exception e) {
        	logger.error("exportFile page is Exception!");
            e.printStackTrace();
        }
        return "redirect:show.htm";
    }
    
    
     /**
     * 
     * 功能描述: <br>
     * 下载导入模板
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "importTemplate")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "残疾人住房补助信息导入模板.xlsx";
            List<ClQtbzCjrzfbzDTO> list = new ArrayList<>(); 
            list.add(new ClQtbzCjrzfbzDTO());
            new ExportExcel("残疾人住房补助信息数据", ClQtbzCjrzfbzDTO.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/sys/clQtbzCjrzfbz/show";
    }

    
    /**
     * 
     * 功能描述: <br>
     * 去导入界面
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @GetMapping("toImport")
    public String toImport() {
        return "sys/clQtbzCjrzfbz/import_excel";
    }
    
    /**
     * 
     * 功能描述: <br>
     * 导入
     *
     * @param file
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("importFile")
    @ResponseBody
    public ResultVO<ImportResultVO> importFile(MultipartFile file, @RequestParam(required = false, value="param") String param) {
        JSONObject json = JSON.parseObject(param);
        logger.error(json!=null?json.toJSONString():"");
        int successNum=0;
        int failureNum=0;
        StringBuilder failureMsg=new StringBuilder();
        ImportExcel ei;
        List<ClQtbzCjrzfbzDTO> list;
        try {
            ei = new ImportExcel(file, 1, 0);
            list=ei.getDataList(ClQtbzCjrzfbzDTO.class);
        } catch (Exception e1) {
            e1.printStackTrace();
            list = new ArrayList<>(); 
        }
        for(ClQtbzCjrzfbzDTO data : list) {
               data.setUpdateTime(new Date());
               data.setIsDel(Contant.is_del_undelete);
               data.setCreateTime(new Date());
               try {
                   IClQtbzCjrzfbzService.saveOrUpdate(data);
                   successNum++;
               } catch (Exception e) {
                   e.printStackTrace();
                   failureNum++;
                   failureMsg.append("数据：").append(JSON.toJSONString(data)).append("导入失败；");
               }
        }
        return ResultVO.success(ImportResultVO.result(successNum, failureNum, failureMsg.toString()), ResultVO.SUCCESS, ResultVO.errors.get(ResultVO.SUCCESS));
    }
	
}
